<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>客户箱量情况</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div id="takeoutMain">
      <a-form layout="inline" ref="form" :model="form">
        <a-form-item label="客户名称">
          <a-auto-complete @select="onSelect" @search="onSearch" @change="custIdChange">
            <template slot="dataSource">
              <a-select-option
                v-for="(record,index) in custNameList"
                :key="index"
                :value="record.name"
              >{{ record.name }}</a-select-option>
            </template>
          </a-auto-complete>
        </a-form-item>
        <a-form-item label="选择日期">
          <a-range-picker @change="onChange">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
        </a-form-item>
        <a-form-item label="所属部门">
          <a-tree-select
            class="selectInputWidth"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
            placeholder="请选择"
            @change="onChangeTree"
          ></a-tree-select>
        </a-form-item>
        <a-form-item label="所属销售">
          <a-select v-model="form.sellerId" class="selectInputWidth">
            <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="check">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="excelExport">导出Excel</a-button>
        </a-form-item>
      </a-form>
      <a-card style="text-align:center; margin-top:24px;">
        <a-row :gutter="[16]">
          <a-col :span="12" class="assent">
            <div class="assent_mes">客户数量</div>
            <div class="assent_shu">{{statisticsObj.custQuantity}}</div>
          </a-col>
          <a-col :span="12">
            <div class="assent_mes">总箱量</div>
            <div class="assent_shu">{{statisticsObj.completeQuantity}}</div>
          </a-col>
        </a-row>
      </a-card>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="tableData"
        class="tableMargin"
        :pagination="pagination"
        :row-key="(record,index) => index"
      >
        <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
        <template slot="name" slot-scope="text, record">
          <a @click="toCustomer(record.custId)">{{record.custName}}</a>
        </template>
        <template slot="operation" slot-scope="record">
          <a @click="detail(record)">查看</a>
        </template>
      </a-table>
    </div>
    <a-modal
      v-model="visible"
      title="箱量详情"
      :body-style="{padding:'24px 40px 0px 20px'}"
      :width="1000"
      centered
      :footer="null"
      destroyOnClose
    >
      <a-form layout="inline" ref="detailForm" :model="detailForm">
        <a-form-item label="箱量统计日期">
          <a-range-picker @change="detailTimeChange" :value="detailTimeValue">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="detailCheck">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="detailExport">导出Excel</a-button>
        </a-form-item>
      </a-form>
      <a-table
        :loading="detailLoading"
        :columns="detailColumns"
        :data-source="detailData"
        class="tableMargin"
        :pagination="detailPagination"
        :row-key="(record,index) => index"
      >
        <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
        <template slot="companyId" slot-scope="text, record">
          <a v-if="record.shipOrderCode" @click="toCompanyDetail(record)">{{record.shipOrderCode}}</a>
          <span v-else>--</span>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import { commonExport } from '@/api/request'
import moment from 'moment'
import { querySellerDown, queryDeptDown } from '@/api'
import {
  queryCustNameList,
  queryCustContainerList,
  queryCustContainerDetail
} from '@/api/salesCenter'
import _ from 'lodash/debounce'
const deptData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}
const columns = [
  {
    title: '序号',
    width: 60,
    scopedSlots: { customRender: 'rn' }
  },
  {
    title: '客户名称',
    dataIndex: 'custName',
    scopedSlots: {
      customRender: 'name'
    }
  },
  {
    title: '客户类型',
    dataIndex: 'isCompany',
    _needName: true,
    customRender: (text, record, index) => {
      return record.isCompany ? '企业客户' : '个人客户'
    }
  },
  {
    title: '所属销售',
    dataIndex: 'seller'
  },
  {
    title: '所属部门',
    dataIndex: 'department'
  },
  {
    title: '箱量（个）',
    dataIndex: 'completeQuantity',
    customRender: (text, record, index) => {
      return record.completeQuantity || '--'
    }
  },
  {
    title: '操作',
    width: 100,
    scopedSlots: { customRender: 'operation' }
  }
]
const detailColumns = [
  {
    title: '序号',
    width: 60,
    scopedSlots: { customRender: 'rn' }
  },
  {
    title: '公司编号',
    dataIndex: 'shipOrderCode',
    width: 150,
    scopedSlots: { customRender: 'companyId' }
  },
  {
    title: '箱量统计日期',
    dataIndex: 'loadingTime',
    customRender: (text, record, index) => {
      return record.loadingTime || '--'
    }
  },
  {
    title: '运单号',
    dataIndex: 'seagoingShipOrderCode',
    customRender: (text, record, index) => {
      return record.seagoingShipOrderCode || '--'
    }
  },
  {
    title: '箱号',
    dataIndex: 'containerNo',
    customRender: (text, record, index) => {
      return record.containerNo || '--'
    }
  },
  {
    title: '箱封号',
    dataIndex: 'containerSealNo',
    customRender: (text, record, index) => {
      return record.containerSealNo ? record.containerSealNo : '--'
    }
  },
  {
    title: '箱型',
    dataIndex: 'containerType',
    customRender: (text, record, index) => {
      return record.containerType || '--'
    }
  },
  {
    title: '货名',
    dataIndex: 'goodsName',
    customRender: (text, record, index) => {
      return record.goodsName || '--'
    }
  }
]
export default {
  data () {
    this.onSearch = _(this.onSearch, 800)
    return {
      loading: true,
      custNameList: [],
      columns,
      form: {
        deptId: '', // 所属部门id
        sellerId: '', // 销售id
        custId: '', // 客户id
        startDate: '',
        endDate: ''
      },
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      statisticsObj: {},
      pagination: {},
      visible: false,
      detailColumns,
      detailForm: {
        custId: '',
        startDate: '',
        endDate: ''
      },
      detailTimeValue: [],
      startMonth: '',
      endMonth: '',
      detailLoading: true,
      detailData: [],
      detailPagination: {},
      detailPageNum: 1,
      detailPageSize: 10,
      deptTreeData: [],
      sellers: [],
      isFirstEnd: true
    }
  },
  methods: {
    sellExamineListRequest (e) {
      this.loading = true
      queryCustContainerList(e)
        .then(res => {
          this.isFirstEnd = false
          this.tableData = res.data.rspQueryCustContainerList.list
          this.statisticsObj = res.data.rspCustContainerStatistics
          let currentPage = this.pageNum
          this.pagination = {
            current: currentPage,
            pageSize: res.data.rspQueryCustContainerList.pageSize,
            total: res.data.rspQueryCustContainerList.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.rspQueryCustContainerList.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.sellExamineListRequest(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.sellExamineListRequest(paramData)
            }
          }
          this.loading = false
        })
        .catch(rs => { })
    },
    shipOrderListRequest (e) {
      this.detailLoading = true
      queryCustContainerDetail(e)
        .then(res => {
          this.detailData = res.data.list
          let currentPage = this.detailPageNum
          this.detailPagination = {
            current: currentPage,
            pageSize: res.data.pageSize,
            total: res.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.pages}页`,
            onChange: pageNum => {
              this.detailPageNum = pageNum
              let paramData = {
                pageSize: this.detailPageSize,
                pageNum: this.detailPageNum,
                ...this.detailForm
              }
              this.shipOrderListRequest(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.detailPageNum = current
              this.detailPageSize = size
              let paramData = {
                pageSize: this.detailPageSize,
                pageNum: this.detailPageNum,
                ...this.detailForm
              }
              this.shipOrderListRequest(paramData)
            }
          }
          this.detailLoading = false
        })
        .catch(rs => { })
    },
    custNameListRequest (e) {
      queryCustNameList(e)
        .then(res => {
          this.custNameList = res.data
        })
        .catch(rs => { })
    },
    onSearch (searchText) {
      this.custNameListRequest({
        status: 1,
        nameLike: searchText,
        belongCompany: 'JIA_HUA',
        custTypeLike: 'CUSTOMER'
        // isPayable: 1
      })
    },
    onSelect (val, option) {
      // console.log(val)
      this.form.custId = this.custNameList[option.key].id
    },
    custIdChange (val) {
      if (val.length === 0) {
        this.form.custId = ''
      }
    },
    onChange (date, dateString) {
      this.form.startDate = dateString[0]
      this.form.endDate = dateString[1]
    },
    toCustomer (id) {
      window.open(`/salesCenter/customManage/${id}`, '_blank')
    },
    check () {
      this.startMonth = this.form.startDate
      this.endMonth = this.form.endDate
      this.sellExamineListRequest({
        ...this.form,
        pageNum: 1,
        pageSize: 10
      })
    },
    excelExport () {
      commonExport('/sales/exportCustContainerList', {
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    },
    detail (e) {
      this.detailPageNum = 1
      this.detailPageSize = 10
      this.detailTimeValue = this.startMonth ? [moment(this.startMonth), moment(this.endMonth)] : []
      this.detailForm = {
        startDate: this.startMonth,
        endDate: this.endMonth,
        custId: e.custId
      }
      this.shipOrderListRequest({
        ...this.detailForm,
        pageNum: this.detailPageNum,
        pageSize: this.detailPageSize
      })
      this.visible = true
    },
    detailTimeChange (date, dateString) {
      this.detailTimeValue = date
      this.detailForm.startDate = dateString[0]
      this.detailForm.endDate = dateString[1]
    },
    detailCheck () {
      this.detailPageNum = 1
      this.detailPageSize = 10
      this.shipOrderListRequest({
        ...this.detailForm,
        pageNum: this.detailPageNum,
        pageSize: this.detailPageSize
      })
    },
    detailExport () {
      commonExport('/sales/exportCustContainerDetail', {
        ...this.detailForm,
        pageNum: this.detailPageNum,
        pageSize: this.detailPageSize,
        columns: this.detailColumns
      })
    },
    toCompanyDetail (e) {
      window.open(`/orderCenter/order/detail/${e.shipOrderId}`, '_blank')
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          rsp => {
            let childrenData = []
            rsp.data.forEach(value => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      queryDeptDown(e).then(rsp => {
        let initData = []
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId
          })
        })
        this.deptTreeData = initData
        this.form.deptId = rsp.data[0].deptId
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      return new Promise(resolve => {
        querySellerDown({ ...sellerData, deptId }).then(rsp => {
          this.sellers = rsp.data.map((v, i) => {
            if (!v.uiId) {
              v.name = '请选择'
              v.uiId = ''
            }
            return v
          })
          this.form.sellerId = rsp.data[0].uiId
          if (this.isFirstEnd) {
            resolve(this.form)
          }
        })
      }).then(res => {
        this.sellExamineListRequest({
          ...this.form,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
      })
    }
  },
  mounted () {
    // 所属部门
    this.initDept(deptData)
    // 所属销售
    this.initSellerDown()
  }
}
</script>

<style lang="less" scoped>
#takeoutMain {
  padding: 24px;
  margin: 24px;
  background: #fff;
  min-height: 700px;
}
</style>
